package cn.numeron.common.extension

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

private val formatterThreadLocal = ThreadLocal<SimpleDateFormat>()

private val formatter
    get() = formatterThreadLocal.get()
        ?: (DateFormat.getDateTimeInstance() as SimpleDateFormat)
            .also(formatterThreadLocal::set)

const val DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"

fun Date.format(pattern: String = DEFAULT_DATETIME_PATTERN): String {
    formatter.applyPattern(pattern)
    return formatter.format(this)
}

fun Long.format(pattern: String = DEFAULT_DATETIME_PATTERN): String {
    formatter.applyPattern(pattern)
    return formatter.format(this)
}

fun String.parse(pattern: String = DEFAULT_DATETIME_PATTERN): Date {
    formatter.applyPattern(pattern)
    return formatter.parse(this)
}